package com.comment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.comment.dto.Result;
import com.comment.dto.UserDTO;
import com.comment.entity.Follow;
import com.comment.entity.User;
import com.comment.mapper.FollowMapper;
import com.comment.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comment.service.IUserService;
import com.comment.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;
    /**
     * 关注或取关
     *
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        // 1.判断到底是关注还是取关
        if (isFollow){
            // 2.实现关注逻辑，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            // 2.1.判断关注是否成功
            boolean isSuccess = save(follow);
            if (isSuccess){
                // 2.2把关注的用户id存入Redis的Set集合
                stringRedisTemplate.opsForSet().add("follows:" + userId, followUserId.toString());
            }
        }else {
            // 3.实现取关逻辑，删除数据
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId).eq("follow_user_id", followUserId));
            if (isSuccess){
                // 3.1.把取关的用户id从Redis的Set集合中移除
                stringRedisTemplate.opsForSet().remove("follows:" + userId, followUserId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 判断是否关注
     *
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        // 1.查询是否关注
        Long userId = UserHolder.getUser().getId();
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        // 2.返回判断结果
        return Result.ok(count > 0);
    }

    /**
     * 查看共同关注
     *
     * @param id
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        // 1.获取当前用户id
        Long userId = UserHolder.getUser().getId();
        // 2.查询两个Set集合的交集
        String key1 = "follows:" + userId;
        String key2 = "follows:" + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if (intersect == null || intersect.isEmpty()){
            // 无交集
            return Result.ok(Collections.emptyList());
        }
        // 3.解析id的Set集合为Long集合
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 4.根据id集合查询用户
        Stream<UserDTO> users = userService.listByIds(ids).stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class));
        // 5.返回结果
        return Result.ok(users);
    }
}
